package views;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import navigation.MapService;
import navigation.NavigationDataSet;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Path.Direction;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;

import com.example.android.google.apis.R;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;

public class MapDirections extends MapActivity implements LocationListener {

    private MyLocationOverlay me = null;
    private MapView map;

    public void onCreate(Bundle previous) {

	super.onCreate(previous);
	requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
	setContentView(R.layout.maps);
	getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.banner);
	map = (MapView) findViewById(R.id.map);
	Bundle b = getIntent().getExtras();

	me = ((MyOverlay) b.get("me_overlay")).getOverlay();
	
	map.getOverlays().add(0, me);
	LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

	Location lastLoc = locationManager
		.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

	locationManager.requestLocationUpdates(
		LocationManager.NETWORK_PROVIDER, 5000, 10, this);
	locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
		6000, 50, this);

	NavigationDataSet nds = MapService.calculateRoute(
		b.getDouble("me_lat"), b.getDouble("me_lon"),
		b.getDouble("dest_lon"), b.getDouble("dest_lat"),
		MapService.MODE_WALKING);
	drawPath(nds, 1661649, map);
    }

    /**
     * Does the actual drawing of the route, based on the geo points provided in
     * the nav set
     * 
     * @param navSet
     *            Navigation set bean that holds the route information, incl.
     *            geo pos
     * @param color
     *            Color in which to draw the lines
     * @param mMapView01
     *            Map view to draw onto
     */
    public void drawPath(NavigationDataSet navSet, int color, MapView mMapView01) {

	Log.d("NAV", "map color before: " + color);

	// color correction for dining, make it darker
	if (color == Color.parseColor("#add331"))
	    color = Color.parseColor("#6C8715");
	Log.d("NAV", "map color after: " + color);

	Collection overlaysToAddAgain = new ArrayList();
	for (Iterator iter = mMapView01.getOverlays().iterator(); iter
		.hasNext();) {
	    Object o = iter.next();
	    Log.d("NAV", "overlay type: " + o.getClass().getName());
	    if (!RouteOverlay.class.getName().equals(o.getClass().getName())) {
		// mMapView01.getOverlays().remove(o);
		overlaysToAddAgain.add(o);
	    }
	}
	mMapView01.getOverlays().clear();
	mMapView01.getOverlays().addAll(overlaysToAddAgain);

	String path = navSet.getRoutePlacemark().getCoordinates();
	Log.d("NAV", "path=" + path);
	if (path != null && path.trim().length() > 0) {
	    String[] pairs = path.trim().split(" ");

	    Log.d("NAV", "pairs.length=" + pairs.length);

	    String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude
						   // lngLat[1]=latitude
						   // lngLat[2]=height

	    Log.d("NAV", "lnglat =" + lngLat + ", length: " + lngLat.length);

	    if (lngLat.length < 3)
		lngLat = pairs[1].split(","); // if first pair is not
					      // transferred completely, take
					      // seconds pair //TODO

	    try {
		GeoPoint startGP = new GeoPoint(
			(int) (Double.parseDouble(lngLat[1]) * 1E6),
			(int) (Double.parseDouble(lngLat[0]) * 1E6));
		mMapView01.getOverlays().add(
			new RouteOverlay(startGP, startGP, 1));
		GeoPoint gp1;
		GeoPoint gp2 = startGP;

		for (int i = 1; i < pairs.length; i++) // the last one would be
						       // crash
		{
		    lngLat = pairs[i].split(",");

		    gp1 = gp2;

		    if (lngLat.length >= 2 && gp1.getLatitudeE6() > 0
			    && gp1.getLongitudeE6() > 0
			    && gp2.getLatitudeE6() > 0
			    && gp2.getLongitudeE6() > 0) {

			// for GeoPoint, first:latitude, second:longitude
			gp2 = new GeoPoint(
				(int) (Double.parseDouble(lngLat[1]) * 1E6),
				(int) (Double.parseDouble(lngLat[0]) * 1E6));

			if (gp2.getLatitudeE6() != 22200000) {
			    mMapView01.getOverlays().add(
				    new RouteOverlay(gp1, gp2, 2, color));
			    Log.d("NAV",
				    "draw:" + gp1.getLatitudeE6() + "/"
					    + gp1.getLongitudeE6() + " TO "
					    + gp2.getLatitudeE6() + "/"
					    + gp2.getLongitudeE6());
			}
		    }
		    // Log.d("NAV","pair:" + pairs[i]);
		}
		// routeOverlays.add(new RouteOverlay(gp2,gp2, 3));
		mMapView01.getOverlays().add(1, new RouteOverlay(gp2, gp2, 3));
	    } catch (NumberFormatException e) {
		Log.e("NAV", "Cannot draw route.", e);
	    }
	}
	// mMapView01.getOverlays().addAll(routeOverlays); // use the default
	// color
	mMapView01.setEnabled(true);
    }

    @Override
    public void onLocationChanged(Location loc) {

	List<Overlay> mapOverlays = map.getOverlays();
	if (mapOverlays.get(0) != null)
	    mapOverlays.remove(0);
	map.getOverlays().add(0, me);
	MapController mapController = map.getController();
	GeoPoint p = getPoint(loc.getLatitude(), loc.getLongitude());
	mapController.animateTo(p);
	map.invalidate();
    }

    private GeoPoint getPoint(double lat, double lon) {
	return (new GeoPoint((int) (lat * 1000000.0), (int) (lon * 1000000.0)));
    }

    @Override
    public void onProviderDisabled(String provider) {
	// TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
	// TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
	// TODO Auto-generated method stub

    }

    @Override
    protected boolean isRouteDisplayed() {
	// TODO Auto-generated method stub
	return false;
    }

    @Override
    public void onResume() {

	me.enableCompass();
	me.enableMyLocation();
	super.onResume();
    }

}
